import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/department/:id',
    name: 'Department',
    component: () => import('@/views/Department.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/appointments',
    name: 'DoctorAppointments',
    component: () => import('@/views/doctor/Appointments.vue'),
    meta: { requiresAuth: true, role: 2 }
  },
  {
    path: '/consultations',
    name: 'DoctorConsultations',
    component: () => import('@/views/doctor/Consultations.vue'),
    meta: { requiresAuth: true, role: 2 }
  },
  {
    path: '/doctor',
    component: () => import('@/layouts/DoctorLayout.vue'),
    meta: { requiresAuth: true, role: 1 },
    children: [
      {
        path: 'appointments',
        component: () => import('@/views/doctor/Appointments.vue'),
        meta: { requiresAuth: true, role: 1 },
      },
      {
        path: 'consultations',
        component: () => import('@/views/doctor/Consultations.vue'),
        meta: { requiresAuth: true, role: 1 },
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const user = JSON.parse(localStorage.getItem('user'));

  if (to.meta.requiresAuth && !token) {
    next('/login');
  } else if (to.meta.role && user.type !== to.meta.role) {
    next(user.type === 1 ? '/doctor/appointments' : '/home');
  } else {
    next();
  }
});

export default router;
